"""
Copyright (c) 2022 Guangdong University of Technology
PhotLab is licensed under [Open Source License].
You can use this software according to the terms and conditions of the [Open Source License].
You may obtain a copy of [Open Source License] at: [https://open.source.license/]

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.

See the [Open Source License] for more details.

Author: Meng Xiang
Created: 2023/8/19
Supported by: National Key Research and Development Program of China
"""


import numpy as np

import phot


def attenuator(input, attenuation = 0, active = 1):
    '''
    该模块用于将输入的光信号的光电场强度按所设定的衰减系数进行衰减
    #attenuation衰减系数，单位为dB
    #active为模块开关，1开启，0关闭
    '''

    if active == 0:
        print("attenuator is not working!")
        return input
    if active != 1:
        raise ValueError('active 需为0或1！')
    if attenuation < 0:
        raise ValueError('attenuation 要大于等于0！')

    # output_atteuation = input / 10 ** (attenuation/20)

    loss_alpha = np.log(10 ** (attenuation / 10)) / 2
    Hf = np.exp(-loss_alpha)
    output_atteuation = np.fft.ifft(np.fft.fft(input) * Hf)

    return output_atteuation


if __name__ == "__main__":
    """ 参考 VPI """

    phot.config(plot=True, backend="numpy")  # 全局开启画图，backend 使用 numpy

    # 设置全局系统仿真参数
    num_symbols = 2**16  # 符号数目
    bits_per_symbol = 6  # 2 for QPSK; 4 for 16QAM; 6 for 64QAM  设置调制格式
    total_baud = 64e9  # 信号波特率，符号率
    up_sampling_factor = 4  # 上采样倍数
    sampling_rate = up_sampling_factor * total_baud  # 信号采样率
    Reference_frequency = 193.1e12

    # 首先产生发射端X/Y双偏振信号
    signal_bits = phot.gen_bits(num_symbols * bits_per_symbol)

    # 生成双偏振符号序列 #
    signals = phot.Modulation(signal_bits, bits_per_symbol)

    data = signals[0]

    print(np.mean(abs(data)**2))

    out = attenuator(data, 2)

    print(np.mean(abs(out)**2))


